#!/bin/bash

env

JENKINS_OPS="${JENKINS_OPS} -Dhudson.lifecycle=hudson.lifecycle.ExitLifecycle"

JENKINS_PARAM="${JENKINS_PARAM} --httpPort=${JENKINS_MANAGE_PORT}"
JENKINS_PARAM="${JENKINS_PARAM} --logfile=${JENKINS_HOME}/logs/runlog.log"

mkdir -p /srv/jenkins/{data,logs}
touch ${JENKINS_HOME}/logs/runlog.log
touch ${JENKINS_HOME}/logs/jenkins.log

echo "Begin start ${RUN_JAVA_HOME}/bin/java ${JENKINS_OPS} -jar /opt/env/jenkins/jenkins.war ${JENKINS_PARAM} $@ ..."
${RUN_JAVA_HOME}/bin/java ${JENKINS_OPS} -jar /opt/env/jenkins/jenkins.war ${JENKINS_PARAM} $@ &
pre_pid=$!

if [ -z ${pre_pid} ]; then
    echo "Failed to start !!!"
    exit 1
fi

sleep 60
if [ -f ${JENKINS_HOME}/secrets/initialAdminPassword ]; then
    echo 'First startup, need initial config'
    kill -9 ${pre_pid}
else
    tail -f /dev/null
    exit 0
fi

sed -i 's#https://updates.jenkins.io/update-center.json#https://mirrors.huaweicloud.com/jenkins/update-center.json#g' ${JENKINS_HOME}/hudson.model.UpdateCenter.xml
sed -i 's#https://updates.jenkins.io/download/plugins#https://mirrors.aliyun.com/jenkins/plugins#g' ${JENKINS_HOME}/updates/default.json
sed -i 's#https://www.google.com#https://www.baidu.com#g' ${JENKINS_HOME}/updates/default.json

${RUN_JAVA_HOME}/bin/java ${JENKINS_OPS} -jar /opt/env/jenkins/jenkins.war ${JENKINS_PARAM} $@
echo "Error, jenkins exit, code $?"